var date
var x;
var y;
var sportId;
var sleepId;
var getUpId;
var marker;
var money;
var bm;
$.getJSON("/map/getConfig/", function (json) {
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: configAppId, // 必填，公众号的唯一标识
        timestamp: json.timeStamp, // 必填，生成签名的时间戳
        nonceStr: json.nonceStr, // 必填，生成签名的随机串
        signature: json.signature,// 必填，签名
        jsApiList: [
            'openLocation',
            'getLocation',
            'closeWindow'
        ] // 必填，需要使用的JS接口列表，所有JS接口列表见官方文档附录2
    });
    wx.ready(function () {
        var Reqx;
        var Reqy;
        var openId;
        var doEventId;
        var eventName;
        var eventID;
        date = new Date();
        var userId;
        var day = ("0" + date.getDate()).slice(-2);
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var nowDate = date.getFullYear()+"-"+(month)+"-"+(day);
        console.log("nowDate|"+nowDate);
        // alert("nowDate|"+nowDate);
        bm = new BMap.Map("allmap");
        getLocation();
        sport();
        sleep();
        getUP();
        console.log("this is ready");
        $.getJSON("/map/getOpenId/", function (json) {
            openId = json.openId;
            var nowTime = new Date();
            var user = {openId: openId};
            $.ajax({
                type: "get",
                url: "/doEvent/getUserByOpenId",    //通过OpenId 获取用户中心 user的信息
                cache: false,
                async: false,
                data: user,
                dataType: "json",
                success: function (data) {
                    if(data[0]==null){
                        alert("请绑定用户！");
                        var url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + configAppId + "&redirect_uri=";           //String url2="&redirect_uri=";
                        var url2 = "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
                        window.location.href = url1 + url + "/page/bangDingToUser" + url2;
                        return;
                    }else {
                        userId = data[0].id;

                    }

                    checkEvents();                          //根据userId  查找需要的打卡项
                }
            })
            $("#btn_click").click(function () {//button    button    button    button    button*******************
                checkLocation(eventName);//检查是否需要地理位置验证
            })

            function checkLocation(eventName) {
                var event = {
                    name: eventName
                }

                $.ajax({
                    type: "POST",
                    url: "/event/getLocationsByEventName",   //获得该项打卡地理位置
                    data: event,
                    async: false,
                    cache: false,
                    dataType: "json",
                    success: function (data) {
                        if (data.result == "success") {
                            var locations = data.locations;
                            checkLocations(locations);

                        } else {
                            //该项不需要地理位置验证！
                            //插入数据
                            var doEvent = {
                                id: doEventId
                            }
                            $.ajax({
                                type: "post",
                                data: doEvent,
                                dataType: "json",
                                async: false,
                                url: "/doEvent/updateUserEvent2",
                                success: function (data) {
                                    swal(eventName+"打卡成功！", "勤学金+"+money+"元\n该项执行力100%、信誉度100%", "success");
                                   // setTimeout(wx.closeWindow,4000);

                                   // alert(eventName+"打卡成功！"+"\n勤学金+"+money+"元\n该项执行力100%、信誉度100%");
                                    $("#btn_click").hide();
                                    responseMessage();
                                   // wx.closeWindow();
                                }
                            })
                        }
                    },
                    error: function () {
                        swal("打卡失败", "", "error");
                        alert("打卡失败！");
                    }

                })

                function getLocationById(locationId) {
                    var location = {
                        id: locationId
                    }
                    $.ajax({
                        type: "post",
                        data: location,
                        url: "/location/getLocationById",
                        async: false,
                        dataType: 'json',
                        success: function (data) {
                            Reqx = data[0].x;
                            Reqy = data[0].y;
                        }
                    })
                }
            }
        });


        function checkEvents() {
            var doEvent = {
                userId: userId,
            };
            $.ajax({
                type: "post",
                url: "/doEvent/checkEvents",
                cache: false,
                async: false,
                data: doEvent,
                dataType: "json",
                success: function (data) {
                    if (data == null || data == "") {
                        swal("今日没有作训科目！", "", "success");
                       // setTimeout(wx.closeWindow,4000);
                        // alert("今日没有作训科目！");
                        // wx.closeWindow();
                    } else {
                        getEventsById(data);    //遍历所有的打卡项
                        if (eventID == getUpId) {
                            checkGetUP();//检查午睡有没有打卡
                        }
                        if (eventID == sportId) {       //做运动
                            $.ajax({
                                type: "get",
                                data: {
                                    id: doEventId
                                },
                                dataType: "text",
                                async: false,
                                url: "/doEvent/getDoEventById",
                                success: function (data) {
                                    if (data == -1) {
                                        $("#btn_click").hide();
                                        var url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + configAppId + "&redirect_uri=";           //String url2="&redirect_uri=";
                                        var url2 = "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
                                        window.location.href = url1 + url + "/page/sport" + url2;
                                    }
                                }
                            })
                        }
                    }
                }

            })

            function getEventsById(data) {
                for (var i in data) {
                    doEventId = data[i].id;
                    var startTime;
                    var endTime;
                    var eventId2 = data[i].eventId;
                    var event = {
                        id: eventId2
                    }
                    eventID = eventId2;
                    getEvent(event);//通过打卡id返回该项打卡的时间要求
                    checkResultByDoEventId();
                    var userId;
                    var nowTime = two_char(date.getHours()) + ":" + two_char(date.getMinutes()) + ":" + two_char(date.getSeconds())

                    function two_char(n) {
                        return n >= 10 ? n : "0" + n;
                    }

                    if (startTime < nowTime && nowTime < endTime) {//查找当前时间段存在的打卡项
                        $("#btn_click").text(eventName)

                        break;
                    }
                    if (eventName == null || eventName == "") {
                        swal("该项已打卡！！！！", "", "success");
                       // setTimeout(wx.closeWindow,4000);
                        // alert("该项已打卡！！！");
                        // wx.closeWindow();
                    }
                    if (nowTime > endTime || nowTime < startTime) {
                        $("#btn_click").css("display", "none");
                        doEventId = null;
                        eventName = "";
                    }
                    $("#btn_click").text(eventName);

                }
                if(eventName==null||eventName==""){
                    swal("此时没有作训科目！", "", "success");
                   // setTimeout(wx.closeWindow,4000);
                }
                function getEvent(event) {
                    $.ajax({
                        type: "post",
                        url: "/event/getEventsById",
                        cache: false,
                        async: false,
                        data: event,
                        dataType: "json",
                        success: function (data2) {
                            startTime = data2.startTime;
                            endTime = data2.endTime;
                            eventName = data2.eventName;
                            money=data2.money;

                        }
                    })
                }//getEvent  end!!!!
            }//getEventsById  end!!!!

            function checkResultByDoEventId() {
                $.ajax({
                    type: "get",
                    data: {
                        id: doEventId
                    },
                    dataType: "text",
                    async: false,
                    url: "/doEvent/getDoEventById",
                    success: function (data) {
                        if (data == -1) {

                            //getLocation();
                            $("#btn_click").css('display', "inline-block")
                        } else if (data == 0) {
                            swal("做运动已打卡！成绩不合格！", "", "error");
                           // setTimeout(wx.closeWindow,4000);
                            // alert("做运动已打卡！成绩不合格！");
                            // wx.closeWindow();
                        }
                        // else if (data==1){
                        //     alert("该项已打卡！");
                        //     getLocation();
                        //    // $("#btn_click").css('display','none');
                        //     wx.closeWindow();
                        // }
                    }
                })
            }

            function checkGetUP() {
                var doEvent = {
                    userId: userId,
                    eventId: sleepId,
                    date: nowDate
                }
                $.ajax({
                    type: "get",
                    data: doEvent,
                    dataType: 'text',
                    url: "/doEvent/getDoEvent",
                    success: function (data) {
                        if (data == -1) {
                            $("#btn_click").css('display', 'none');
                            swal("午睡没有打卡！", "", "error");
                            //setTimeout(wx.closeWindow,4000);
                            // alert("午睡没有打卡！");
                            //getLocation();
                            // wx.closeWindow();
                        }
                    }
                })
            }
        }//checkEvents  end!!!!

        function checkLocations(locations) {
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                async: false,
                success: function (res) {
                    bm.removeOverlay(marker);
                    console.log("this is get location=========" + res.latitude);
                    console.log("this is get location=========" + res.longitude);
                    x = res.longitude;
                    y = res.latitude;
                    var h_sportType = $("#h_sportType").val();
                    var myPoint = new BMap.Point(x, y);
                    for (var i in locations) {
                        getLocationById1(locations[i]);
                        var targetPoint = new BMap.Point(Reqx, Reqy);
                        //alert("距离目标点：" + bm.getDistance(myPoint, targetPoint).toFixed(2) + "米！");
                        if (bm.getDistance(myPoint, targetPoint).toFixed(2) < 500) {
                            $("#t1").val("1");
                            //插入数据
                            var doEvent = {
                                id: doEventId
                            }
                            $.ajax({
                                type: "post",
                                data: doEvent,
                                dataType: "json",
                                async: false,
                                url: "/doEvent/updateUserEvent2",
                                success: function (data) {
                                    swal(eventName+"打卡成功！", "勤学金+"+money+"元\n该项执行力100%、信誉度100%", "success");
                                  //  setTimeout(wx.closeWindow,4000);
                                   // alert(eventName+"打卡成功！"+"\n勤学金+"+money+"元\n该项执行力100%、信誉度100%");
                                    $("#btn_click").hide();
                                    responseMessage();
                                   // wx.closeWindow();
                                }
                            })
                            break;
                        }
                    }
                    if ($("#t1").val() == "0") {
                        swal("不在打卡范围！", "", "error");
                        //alert("不在打卡范围！");
                    }

                }, cancel: function (res) {

                }
            });
        }

        function getLocationById1(locationId) {
            var location = {
                id: locationId
            }
            $.ajax({
                type: "post",
                data: location,
                url: "/location/getLocationById",
                async: false,
                dataType: 'json',
                success: function (data) {
                    Reqx = data[0].x;
                    Reqy = data[0].y;
                }
            })
        }

        function responseMessage() {
            var responseUser = {
                openId: openId,
                eventName: eventName
            }
            $.ajax({
                type: "post",
                data: responseUser,
                dateType: "text",
                url: "/doEvent/responseMessage",
                async: false,
                success: function (data) {
                }
            })
        }

    });
    wx.error(function (res) {
        console.log("this is error");
    });

    function getLocation() {
        wx.getLocation({

            type: 'wgs84',
            success: function (res) {
                console.log("this is get location=========" + res.latitude);
                console.log("this is get location=========" + res.longitude);
                x = res.longitude;
                y = res.latitude;
                var ggPoint = new BMap.Point(x, y);
                //地图初始化
                bm.centerAndZoom(ggPoint, 18);
                bm.removeOverlay(marker);
                //坐标转换完之后的回调函数
                translateCallback = function (data) {
                    if (data.status === 0) {
                        marker = new BMap.Marker(data.points[0]);
                        bm.addOverlay(marker);
                        var label = new BMap.Label("我的位置", {offset: new BMap.Size(20, -10)});
                        marker.setLabel(label);//添加百度label
                        bm.setCenter(data.points[0]);
                    }
                }
                var convertor = new BMap.Convertor();
                var pointArr = [];
                pointArr.push(ggPoint);
                convertor.translate(pointArr, 1, 5, translateCallback);
            }, cancel: function (res) {

            }
        });
    };


    function sleep() {
        $.ajax({
            type: 'get',
            async: false,
            data: {
                name: sleepName
            },
            dataType: "text",
            url: "/event/getEventIdByName",
            success: function (data) {
                sleepId = data;
            }
        })
    }

    function getUP() {
        $.ajax({
            type: 'get',
            data: {
                name: getUpName
            },
            async: false,
            dataType: "text",
            url: "/event/getEventIdByName",
            success: function (data) {
                getUpId = data;
            }
        })
    }

    function sport() {
        $.ajax({
            type: 'get',
            data: {
                name: sportName
            },
            async: false,
            dataType: "text",
            url: "/event/getEventIdByName",
            success: function (data) {
                sportId = data;
            }
        })
    }


});



